package com.gitee.fanx.retty.spring.springmvc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.fanx.retty.web.PathUtils;
import com.gitee.fanx.retty.web.RouteMapping;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author fanhang
 */
public class SpringMvcRouteMappingRegister {

	private String contextPath;

	private RouteMapping routeMapping;

	private ObjectMapper objectMapper;

	public SpringMvcRouteMappingRegister(String contextPath, RouteMapping routeMapping, ObjectMapper objectMapper) {
		this.contextPath = contextPath;
		this.routeMapping = routeMapping;
		this.objectMapper = objectMapper;
	}

	public void registe(Object bean) {
		String controllerPath = "";
		RequestMapping requestMapping = AnnotationUtils.getAnnotation(bean.getClass(), RequestMapping.class);
		if (requestMapping != null && requestMapping.value().length > 0) {
			Assert.state(requestMapping.value().length == 1, "class [" + bean.getClass() + "] RequestMapping too many parent-path");
			controllerPath = StringUtils.defaultIfBlank(requestMapping.value()[0], "");
		}
		String parentPath = PathUtils.join(contextPath, controllerPath);
		ReflectionUtils.doWithMethods(bean.getClass(), new SpringMappingMethodCallback(routeMapping, parentPath, bean, objectMapper));
	}

}
